import java.util.Arrays;

/**
 * 最小生成树:普利姆算法
 * 给定一个带权的无向连通图，如何选取一棵生成树，使得树上所有边上权的总和最小
 */

public class PrimAlgorithm {


    public static void main(String[] args) {
        char[] data = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G'};
        int verxs = data.length;
        //使用接连矩阵，大数表示两个村子不连接
        int[][] weight = new int[][]{
                {10000, 5, 7, 10000, 10000, 10000, 2},
                {5, 10000, 10000, 9, 10000, 10000, 3},
                {7, 10000, 10000, 10000, 8, 10000, 10000},
                {10000, 9, 10000, 10000, 10000, 4, 10000},
                {10000, 10000, 8, 10000, 10000, 5, 4},
                {2, 3, 10000, 10000, 4, 6, 10000},
        };
        MGraph graph = new MGraph(verxs);
        MinTree minTree = new MinTree();
        minTree.createGraph(graph,verxs,data,weight);
        minTree.showGrap(graph);
        minTree.prim(graph,1);

    }


    //如何修路保证各个村子都能联通并且总的修建总里程最短？

}

class MinTree {
    //创建图的邻接矩阵
    public void createGraph(MGraph graph, int verxs, char[] data, int[][] weight) {
        int i, j;
        for (i = 0; i < verxs; i++) {
            graph.data[i] = data[i];
            for (j = 0; j < verxs; j++) {
                graph.weight[i][j] = weight[i][j];
            }
        }
    }

    //显示图的邻接矩阵
    public void showGrap(MGraph graph) {
        for (int[] link : graph.weight) {
            System.out.println(Arrays.toString(link));
        }
    }

    //prim算法：生成最小树
    public void prim(MGraph graph, int v) {
        int visited[] = new int[graph.verxs];
        visited[v] = 1;
        int h1 = -1;
        int h2 = -1;
        int minWeight = 10000;
        for (int k = 1; k < graph.verxs; k++) {
            for (int i = 1; i < graph.verxs; k++) {
                for (int j = 1; j < graph.verxs; k++) {
                    if (visited[i] ==1 && visited[j]==0&&graph.weight[i][j]<minWeight){
                        minWeight = graph.weight[i][j];
                        h1=i;
                        h2=j;
                    }
                }
            }
            //找到一条最小的边
            System.out.println("边<"+graph.data[h1]+","+graph.data[h2]+">权值："+minWeight);
            visited[h2] =1;
            minWeight = 10000;
        }

    }
}

class MGraph {
    int verxs;//表示节点数
    char[] data;//存放节点数据
    int[][] weight;

    public MGraph(int verxs) {
        this.verxs = verxs;
        data = new char[verxs];
        weight = new int[verxs][verxs];
    }
}
